package mts.messages;

import java.util.Arrays;

import mts.common.CommonSettings;
import mts.constants.Direction;
import mts.constants.MessageType;

public class CarErrorMessage extends Message {
	public static final int INDEX_ERROR_CODE = Message.INDEX_MESSAGE_TYPE + 1;
	public static final int INDEX_FLOOR = INDEX_ERROR_CODE + 1;
	public static final int INDEX_DIRECTION = INDEX_FLOOR + 1;
	public static final int INDEX_HALL_CALLS = INDEX_DIRECTION + 1;
	public static final int MESSAGE_LENGTH = INDEX_HALL_CALLS + CommonSettings.NUMBER_OF_FLOORS;
	

	private byte errorCode;
	private byte floor;
	private Direction direction;
	private byte[] hallCalls;
	
	public byte getErrorCode() {
		return errorCode;
	}

	public byte getFloor() {
		return floor;
	}

	public Direction getDirection() {
		return direction;
	}

	public byte[] getHallCalls() {
		return hallCalls;
	}

	public CarErrorMessage(byte errorCode, byte floor, Direction direction, byte[] hallCalls) {
		this();
		this.errorCode = errorCode;
		this.floor = floor;
		this.direction = direction;
		this.hallCalls = hallCalls;
	}
	
	private CarErrorMessage() {
		super(MessageType.CAR_ERROR);
	}
	
	public static CarErrorMessage deserialize(byte[] data) {
		CarErrorMessage carErrorMessage = new CarErrorMessage();
		carErrorMessage.errorCode = data[INDEX_ERROR_CODE];
		carErrorMessage.floor = data[INDEX_FLOOR];
		carErrorMessage.direction = Direction.valueOf(data[INDEX_DIRECTION]);
		carErrorMessage.hallCalls = Arrays.copyOfRange(data, INDEX_HALL_CALLS, INDEX_HALL_CALLS + CommonSettings.NUMBER_OF_FLOORS);
		
		return carErrorMessage;
	}
	
	@Override
	public byte[] serialize() {
		byte[] data = new byte[MESSAGE_LENGTH];
		data[Message.INDEX_MESSAGE_TYPE] = getMessageType().getByteValue();
		data[INDEX_ERROR_CODE] = errorCode;
		data[INDEX_FLOOR] = floor;
		data[INDEX_DIRECTION] = direction.getByteValue();
		
		for (int i = INDEX_HALL_CALLS; i < INDEX_HALL_CALLS + CommonSettings.NUMBER_OF_FLOORS; i++) {
			data[i] = hallCalls[i - INDEX_HALL_CALLS];
		}
				
		return data;
	}
	
	
	@Override
	public boolean equals(Object other) {
		if (!(other instanceof CarErrorMessage)) {
			return false;
		}
		
		CarErrorMessage o = (CarErrorMessage)other;
		
		return errorCode == o.errorCode &&
				floor == o.floor &&
				direction == o.direction &&
				Arrays.equals(hallCalls, o.hallCalls);				
	}
	
	@Override
	public String toString() {
		return "CarErrorMessage [" +
		"messageType: " + getMessageType() +
		", errorCode: " + errorCode +
		", floor: " + floor +
		", direction: " + direction +
		", hallCalls: " + Arrays.toString(hallCalls) +
		"]";				
	}
	
}
